package com.cxq.boot.provider;

import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.auth.ObjectAuthorization;
import cn.ucloud.ufile.auth.UfileObjectLocalAuthorization;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import cn.ucloud.ufile.http.OnProgressListener;
import com.cxq.boot.exception.CustomizeErrorCode;
import com.cxq.boot.exception.CustomizeException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

@Service
public class UCloudProvider {
    @Value("${ucloud.ufile.public-key}")
    private String publicKey;//公钥
    @Value("${ucloud.ufile.private-key}")
    private String privateKey;//私钥
    @Value("${ucloud.ufile.bucket}")
    private String bucketName;//存储空间名
    @Value("${ucloud.ufile.region}")
    private String region;//地区
    @Value("${ucloud.ufile.proxysuffix}")
    private String proxySuffix;//域名后缀
    @Value("${ucloud.ufile.expiresduration}")
    private int expiresDuration;//地址过期时间

    /**
     * 同步上传文件
     *
     * @param fileStream    输入流
     * @param contentLength 输入流的数据长度，bytesLength
     * @param mimeType      上传的文件类型，如 .jpg .png .av
     * @param filename      文件名
     * @return
     */
    public String upload(InputStream fileStream, long contentLength, String mimeType, String filename) {

        String generatedFileName;
        String[] filePath = filename.split("\\.");
        if (filePath != null) {
            generatedFileName = UUID.randomUUID().toString() + "." + filePath[filePath.length - 1];
        } else {
            throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
        }

        //实例化对象需要用到成员变量值时，需要将实例化对象new写在方法中，而不是类中，否则将无法获取成员变量值，为null值，成员变量在对象创建而存在
        // Bucket相关API的授权器
        ObjectAuthorization bucketAuthorzier = new UfileObjectLocalAuthorization(publicKey, privateKey);
        // 对象操作需要ObjectConfig来配置您的地区和域名后缀
        ObjectConfig config = new ObjectConfig(region, proxySuffix);

        try {
            PutObjectResultBean response = UfileClient.object(bucketAuthorzier, config)
                    .putObject(fileStream, contentLength, mimeType)
                    .nameAs(generatedFileName)
                    .toBucket(bucketName)
                    //是否上传校验MD5, Default = true
                    //  .withVerifyMd5(false)
                    //指定progress callback的间隔, Default = 每秒回调
                    //  .withProgressConfig(ProgressConfig.callbackWithPercent(10))
                    //配置进度监听
                    .setOnProgressListener(new OnProgressListener() {
                        @Override
                        public void onProgress(long bytesWritten, long contentLength) {

                        }
                    })
                    .execute();

            //提示是否上传成功，成功时设置返回带有有限期的图片地址
            if (response != null && response.getRetCode() == 0) {
                String url = UfileClient.object(bucketAuthorzier, config)
                        .getDownloadUrlFromPrivateBucket(generatedFileName, bucketName, expiresDuration)
                        .createUrl();
                //.getDownloadUrlFromPrivateBucket(generatedFileName, bucketName, expiresDuration)
                //expiresDuration – 有效时限 (当前时间开始计算的一个有效时间段, 单位：Unix time second。 eg: 24*60*60 = 1天有效)
                return url;
            } else {
                throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
            }
        } catch (UfileClientException e) {
            e.printStackTrace();
            throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
        } catch (UfileServerException e) {
            e.printStackTrace();
            throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
        }
    }
}
